<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>留言板</title>
    <style>
      body {
        font-family: "Microsoft YaHei", sans-serif;
        margin: 0;
        padding: 20px;
        background: #f5f5f5;
      }

      .container {
        max-width: 1200px;
        margin: 0 auto;
        display: flex;
        gap: 20px;
      }

      .left-section {
        flex: 1;
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      .right-section {
        width: 500px;
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        max-height: calc(100vh - 60px);
        overflow-y: auto;
      }

      .message-form {
        border: 1px solid #ddd;
        padding: 20px;
        border-radius: 4px;
        margin-bottom: 20px;
      }

      .location-select {
        margin-bottom: 15px;
      }

      .location-select select {
        padding: 5px;
        margin-right: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
      }

      .message-input {
        width: 100%;
        min-height: 100px;
        margin: 10px 0;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        resize: vertical;
      }

      .submit-btn {
        background: #8b0000;
        color: white;
        border: none;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
      }

      .submit-btn:hover {
        background: #a00000;
      }

      .message-wall {
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 15px;
      }

      .message-item {
        border-bottom: 1px solid #eee;
        padding: 15px 0;
      }

      .message-header {
        color: #666;
        margin-bottom: 8px;
      }

      .message-location {
        color: #0066cc;
        margin-right: 10px;
      }

      .message-content {
        line-height: 1.6;
      }

      h1,
      h2 {
        text-align: center;
        color: #333;
        margin-bottom: 30px;
      }

      .section-title {
        font-size: 1.2em;
        color: #666;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
      }

      /* 添加响应式样式 */
      @media screen and (max-width: 1200px) {
        .container {
          max-width: 100%;
          padding: 15px;
        }
      }

      @media screen and (max-width: 992px) {
        .container {
          flex-direction: column;
          gap: 20px;
        }

        .right-section {
          width: 100%;
          max-height: 600px;
        }
      }

      @media screen and (max-width: 768px) {
        body {
          padding: 10px;
        }

        .container {
          padding: 10px;
        }

        .left-section,
        .right-section {
          padding: 20px;
        }

        .message-form {
          padding: 15px;
        }

        .location-select {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          align-items: center;
        }

        .location-select select {
          flex: 1;
          min-width: 120px;
        }

        .message-input {
          min-height: 100px;
        }

        h1,
        h2 {
          font-size: 1.5em;
          margin-bottom: 20px;
        }
      }

      @media screen and (max-width: 480px) {
        .container {
          padding: 5px;
        }

        .left-section,
        .right-section {
          padding: 15px;
        }

        .message-form {
          padding: 10px;
        }

        .submit-btn {
          width: 100%;
          padding: 12px;
        }

        .message-item {
          padding: 15px 0;
        }

        .message-header {
          flex-direction: column;
          gap: 5px;
          align-items: flex-start;
        }
      }

      /* 添加暗色模式支持 */
      @media (prefers-color-scheme: dark) {
        body {
          background: #1f1f1f;
          color: #e0e0e0;
        }

        .left-section,
        .right-section {
          background: #2d2d2d;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        .message-form {
          background: #333;
          border-color: #404040;
        }

        .message-input,
        .location-select select {
          background: #2d2d2d;
          border-color: #404040;
          color: #e0e0e0;
        }

        .message-input:focus,
        .location-select select:focus {
          border-color: #177ddc;
        }

        .submit-btn {
          background: #177ddc;
        }

        .submit-btn:hover {
          background: #1890ff;
        }

        .message-item {
          border-bottom-color: #404040;
        }

        .message-item:hover {
          background-color: #333;
        }

        .message-content {
          color: #e0e0e0;
        }

        h1,
        h2 {
          color: #e0e0e0;
        }

        h1::after,
        h2::after {
          background: #177ddc;
        }

        .empty-message,
        .message-header {
          color: #999;
        }
      }

      /* 添加平滑过渡效果 */
      * {
        transition: background-color 0.3s, color 0.3s, border-color 0.3s;
      }

      /* 优化滚动条样式 */
      ::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }

      ::-webkit-scrollbar-track {
        background: transparent;
      }

      ::-webkit-scrollbar-thumb {
        background: #999;
        border-radius: 3px;
      }

      @media (prefers-color-scheme: dark) {
        ::-webkit-scrollbar-thumb {
          background: #666;
        }
      }

      /* 添加加载动画 */
      .loading {
        text-align: center;
        padding: 20px;
      }

      .loading::after {
        content: "";
        display: inline-block;
        width: 30px;
        height: 30px;
        border: 2px solid #f3f3f3;
        border-top: 2px solid #1890ff;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }

      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }

      /* 优化表单交互 */
      .message-input:focus,
      .location-select select:focus {
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
      }

      .submit-btn:active {
        transform: scale(0.98);
      }

      /* 添加消息动画效果 */
      .message-item {
        animation: fadeIn 0.3s ease-out;
      }

      @keyframes fadeIn {
        from {
          opacity: 0;
          transform: translateY(10px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }

      /* 添加成功提示样式 */
      .success-tip {
        background: #e8f5e9;
        color: #2e7d32;
        padding: 10px;
        border-radius: 4px;
        margin-top: 10px;
        text-align: center;
        animation: fadeInOut 3s ease-in-out;
      }

      @keyframes fadeInOut {
        0% {
          opacity: 0;
          transform: translateY(-10px);
        }
        10% {
          opacity: 1;
          transform: translateY(0);
        }
        90% {
          opacity: 1;
          transform: translateY(0);
        }
        100% {
          opacity: 0;
          transform: translateY(-10px);
        }
      }
    </style>
    <script src="area_data.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="left-section">
        <h1>发表留言</h1>
        <div class="message-form">
          <div class="location-select">
            我来自
            <select id="province">
              <option value="">请选择省份</option>
              <!-- 可以添加更多省份 -->
            </select>
            省
            <select id="city">
              <option value="">请选择城市</option>
              <!-- 可以添加更多城市 -->
            </select>
            市
          </div>
          <textarea
            id="messageContent"
            class="message-input"
            placeholder="请输入留言内容..."
          ></textarea>
          <button onclick="addMessage()" class="submit-btn">提 交</button>
        </div>
      </div>

      <div class="right-section">
        <h2>留言墙</h2>
        <div id="messages"></div>
      </div>
    </div>

    <script>
      // 定期刷新时间间隔（毫秒）
      const REFRESH_INTERVAL = 5000;

      // 加载留言列表
      async function loadMessages() {
        try {
          const response = await fetch("get_messages.php");
          if (!response.ok) throw new Error("加载失败");

          const data = await response.json();
          const messages = data.messages;

          const messagesDiv = document.getElementById("messages");
          if (messages.length > 0) {
            let html = "";
            messages.forEach((message) => {
              html += `
                        <div class="message-item">
                            <div class="message-header">
                                <span class="message-location">${escapeHtml(
                                  message.province
                                )}·${escapeHtml(message.city)}</span>
                                <span class="message-time">${formatDate(
                                  message.created_at
                                )}</span>
                            </div>
                            <div class="message-content">${escapeHtml(
                              message.content
                            )}</div>
                        </div>
                    `;
            });
            messagesDiv.innerHTML = html;
          } else {
            messagesDiv.innerHTML = "<p>暂无留言</p>";
          }
        } catch (error) {
          console.error("加载留言失败:", error);
          document.getElementById("messages").innerHTML =
            "<p>加载失败，请刷新页面重试</p>";
        }
      }

      // 添加新留言
      async function addMessage() {
        const content = document.getElementById("messageContent").value.trim();
        const provinceCode = document.getElementById("province").value;
        const cityCode = document.getElementById("city").value;

        if (!content) {
          alert("请输入留言内容");
          return;
        }
        if (!provinceCode || !cityCode) {
          alert("请选择省市");
          return;
        }

        // 获取省市名称
        const province = areaData.provinces.find(
          (p) => p.code === provinceCode
        ).name;
        const city = areaData.cities[provinceCode].find(
          (c) => c.code === cityCode
        ).name;

        try {
          const response = await fetch("save_message.php", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              content: content,
              province: province,
              city: city,
              created_at: formatDateTime(new Date()),
            }),
          });

          if (!response.ok) throw new Error("保存失败");

          document.getElementById("messageContent").value = "";
          loadMessages();

          // 添加成功提示
          const messageForm = document.querySelector(".message-form");
          const successTip = document.createElement("div");
          successTip.className = "success-tip";
          successTip.textContent = "留言发布成功，请等待审核通过后显示";
          messageForm.appendChild(successTip);

          // 3秒后自动移除提示
          setTimeout(() => {
            successTip.remove();
          }, 3000);
        } catch (error) {
          console.error("发布留言失败:", error);
          alert("发布失败，请重试");
        }
      }

      // 添加时间格式化函数
      function formatDateTime(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }

      // 修改显示时间的格式化函数
      function formatDate(dateStr) {
        // 将 "2024-03-20 14:30:45" 转换为 "2024-03-20 14:30"
        return dateStr.substring(0, 16);
      }

      // HTML转义函数，防止XSS攻击
      function escapeHtml(unsafe) {
        return unsafe
          .replace(/&/g, "&amp;")
          .replace(/</g, "&lt;")
          .replace(/>/g, "&gt;")
          .replace(/"/g, "&quot;")
          .replace(/'/g, "&#039;");
      }

      // 添加回车发送功能
      document
        .getElementById("messageContent")
        .addEventListener("keypress", function (e) {
          if (e.key === "Enter" && !e.shiftKey) {
            e.preventDefault();
            addMessage();
          }
        });

      // 初始化省市数据
      function initAreaData() {
        const provinceSelect = document.getElementById("province");
        const citySelect = document.getElementById("city");

        // 清空现有选项
        provinceSelect.innerHTML = '<option value="">请选择省份</option>';
        citySelect.innerHTML = '<option value="">请选择城市</option>';

        // 添加省份选项
        areaData.provinces.forEach((province) => {
          const option = document.createElement("option");
          option.value = province.code;
          option.textContent = province.name;
          provinceSelect.appendChild(option);
        });
      }

      // 处理省份选择变化
      function handleProvinceChange() {
        const provinceCode = document.getElementById("province").value;
        const citySelect = document.getElementById("city");

        // 清空城市下拉框
        citySelect.innerHTML = '<option value="">请选择城市</option>';

        if (provinceCode && areaData.cities[provinceCode]) {
          // 添加对应的城市选项
          areaData.cities[provinceCode].forEach((city) => {
            const option = document.createElement("option");
            option.value = city.code;
            option.textContent = city.name;
            citySelect.appendChild(option);
          });
        }
      }

      // 添加省份选择变化事件监听
      document
        .getElementById("province")
        .addEventListener("change", handleProvinceChange);

      // 页面加载时初始化数据
      document.addEventListener("DOMContentLoaded", () => {
        initAreaData();
        loadMessages();
      });

      // 定期刷新留言列表
      setInterval(loadMessages, REFRESH_INTERVAL);
    </script>
  </body>
</html>
